package cn.test.conf;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;

import org.springframework.http.MediaType;
import org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.ObjectMapper;

public class JsonpHttpMessageConverter extends AbstractJackson2HttpMessageConverter{
	private static final String queryName = "callback";
	
	public JsonpHttpMessageConverter() {
		this(Jackson2ObjectMapperBuilder.json().build());
	}
	
	public JsonpHttpMessageConverter(ObjectMapper objectMapper) {
		super(objectMapper, new MediaType("application", "javascript", DEFAULT_CHARSET));
	}
	
	@Override
	protected void writePrefix(JsonGenerator generator, Object object) throws IOException {
		HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
		if(request == null){
			throw new RuntimeException("cant get HttpServletRequest by RequestContextHolder");
		}
		String jsonpFunction = request.getParameter(queryName);
		generator.writeRaw(jsonpFunction + "(");
	}
	
	@Override
	protected void writeSuffix(JsonGenerator generator, Object object) throws IOException {
		generator.writeRaw(")");
	}
}
